package com.lyq.leetcode.合并区间56;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        int[][] intervals = new int[][]{{3, 8}, {2, 6}, {8, 10}, {15, 18}};
        Main main = new Main();
        System.out.println(Arrays.deepToString(main.merge(intervals)));
    }

    public int[][] merge(int[][] intervals) {
        List<int[]> res = new ArrayList<>();
        Arrays.sort(intervals, (o1, o2) -> o1[0]-o2[0]);
        res.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            int[] last = res.get(res.size()-1);
            if (last[1] >= intervals[i][0]) {
                int max = Math.max(last[1], intervals[i][1]);
                res.set(res.size() - 1, new int[]{last[0], max});
            }else {
                res.add(intervals[i]);
            }
        }
        return res.toArray(new int[0][]);
    }
}
